package com.itheima.servlet;

import com.itheima.service.BrandService;
import com.itheima.bean.Brand;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/add")
public class AddBrand extends HttpServlet {

    private final BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //先设置编码 防止乱码
        req.setCharacterEncoding("UTF-8");
        //获得用户输入的全部参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        System.out.println("获得的请求参数是" + parameterMap.toString());
        //使用工具类将全部参数封装到Brand对象中
        Brand brand = new Brand();
        try {
            BeanUtils.populate(brand,parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        brandService.add(brand);
        //重定向到首页
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       this.doGet(req, resp);
    }
}
